package com.kernowbunney;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

public class SpecViewFragment extends Fragment {
	
	private static final String TAG = "SpecView";
	
	private ImageView mImgView;
	private TextView mStatusText;
	private SeekBar mDateSlider;
	private ProgressBar mImgLoadProgress;

	
	private int mFcHr;
	final private String mURLBase = new String(
			"http://www.ncof.co.uk/~ncof_webuser/spectral_wave/");
	private String mStrSite;
	
	private class DownloadImageHelper extends AsyncTask<URL, Integer, Bitmap> {
		@Override
		protected Bitmap doInBackground(URL... url) {
			Bitmap bm = null;
			
			try {	
				Log.d(TAG, "Connecting to URL: " + url[0].toString());
				URLConnection conn = url[0].openConnection(); 
				Log.d(TAG, "Connection URL is " + conn.getURL().toString()); 
				conn.connect();
				Log.d(TAG, "Connected to URLConnection");
				
				InputStream is = conn.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);
				bm = BitmapFactory.decodeStream(bis);
				bis.close();
				is.close();
				
			} catch (IOException e) {
				Log.e(TAG, "Error in downloading bitmap");
				Log.e(TAG, e.getMessage());
				e.printStackTrace();
				return null;
			}
			
			return bm;
		}
	
	
		// This member function runs in the UI thread, so is safe to update
		// any UI components
		protected void onPostExecute(Bitmap result) {
			if(result != null) {
				// update the ImageView with the downloaded bitmap:
				setCurrentImage(result);		
			} else {
				mStatusText.setText("Problem loading image...");
			}
		}
	}	
	@Override
	public View onCreateView(LayoutInflater inflator, ViewGroup container,
			Bundle savedInstanceState) {
		
		// inflate view:
		View frag = inflator.inflate(R.layout.spec_view_fragment, container, false);
		
		mStatusText = (TextView)frag.findViewById(R.id.specStatusText);
        mDateSlider = (SeekBar)frag.findViewById(R.id.dateSlider);
        mImgView = (ImageView)frag.findViewById(R.id.specImageView);
        mImgLoadProgress = (ProgressBar)frag.findViewById(R.id.imageLoadProgress);
                
        mDateSlider.setMax(60);
        
     
        // restore previous state, if stored:
        if(savedInstanceState != null) {
        	mStatusText.setText("Restored instance state");
        	mFcHr = savedInstanceState.getInt("fchr");
        	mStrSite = savedInstanceState.getString("site");
        	setCurrentImage((Bitmap)savedInstanceState.getParcelable("currentImage"));
        } else {
        	// default values:
            mFcHr = 0;
            mStrSite = "Croyde";
            loadImage();	// load the initial image
        }  
        
        /* Date slider listener */
        mDateSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        	
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// Load an image
				Log.i(TAG, "SeekBar final value: " + seekBar.getProgress());
				mFcHr = seekBar.getProgress();
				loadImage();
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				Log.i(TAG, "SeekBar intermediate value: " + seekBar.getProgress());
				// update date string:
				Calendar c = Calendar.getInstance();	// returns current datetime
				
				// set the time to 00:00:00 on the current day:
				c.set(Calendar.HOUR, 0);
				c.set(Calendar.MINUTE, 0);
				c.set(Calendar.SECOND, 0);
				
				// add the current offset
				c.add(Calendar.HOUR, progress);
				mStatusText.setText(c.getTime().toString());
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
		});
        
		// inflate the layout for this fragment:
		return frag;
	
	}
	
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
    	super.onSaveInstanceState(savedInstanceState);
    	
    	// save the current UI details to the instance state bundle:
    	savedInstanceState.putInt("fchr", mFcHr);
    	savedInstanceState.putString("site", mStrSite);
    	Bitmap bm = ((BitmapDrawable)mImgView.getDrawable()).getBitmap();
    	savedInstanceState.putParcelable("currentImage", bm);
    	
    }
    
	
    public void loadImage() {

    	// gray out the current image whilst loading the new one. Also, show
    	// the spinning progress bar:
    	mImgView.setColorFilter(Color.GRAY, PorterDuff.Mode.DARKEN);
    	mImgLoadProgress.setVisibility(View.VISIBLE);
    	
        mStatusText.setText("Loading forecast T+" + String.format("%03d", mFcHr));
        // download spectral image:
        URL url = null;
        try {
			url = new URL(mURLBase + String.format("nae_%s.%03d.png", 
					mStrSite, mFcHr));
        } catch (MalformedURLException e) {
			//e.printStackTrace();
			mStatusText.setText("Malformed URL!");
        }
        
        //if(mDLImageHelper.getStatus() != AsyncTask.Status.FINISHED)
        //	mDLImageHelper.cancel(true);
        
        // TODO: Cancel the previous AsyncTask, if one is running....
        new DownloadImageHelper().execute(url);
//        mDLImageHelper.execute(url);
        return;
    }
    
    
    private void setCurrentImage(Bitmap bm) {
    	mImgView.setBackgroundColor(Color.WHITE);
		mImgView.setImageBitmap(bm);
		mImgView.setColorFilter(null); // remove image filter (gray out)
		mImgLoadProgress.setVisibility(View.INVISIBLE);
		mStatusText.setText("Complete!");
    }
	
    public void setSite(String site) {
    	mStrSite = site;
    	loadImage();
    }
}
